package com.jade.framework.web.controller;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.jade.framework.base.security.PrincipalCapsule;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.web.ajax.AjaxResult;
import org.springframework.web.servlet.ModelAndView;

/**
 * 控制器工具类.
 *
 * @author lyyang
 * @version 1.0 13-9-8 下午7:17
 * @deprecated
 */
public class ControllerUtils
{

    public static final String JSON_STATUS = "_jade_status_";
    public static void returnSuccess(HttpServletResponse response)
            throws Exception
    {
        PrintWriter out = response.getWriter();
        String result = "{\"_jade_status_\":\"200\"}";
        out.write(result);
        out.flush();
    }

    public static void returnSuccessWithId(HttpServletResponse response,long id) throws Exception
    {
        PrintWriter out = response.getWriter();
        String result = "{\"_jade_status_\":\"200\",\"object_id\":\""+id+"\"}";
        out.write(result);
        out.flush();
    }

    public static <T> AjaxResult getAjaxResult(PagingList<T> list, T[] array, String callback)
    {
        AjaxResult result = new AjaxResult();
        result.setTotal(list.getTotalCount());
        result.setRows(list.toArray(array));
        result.setCallback(callback);
        return result;
    }

    public static <T> AjaxResult getAjaxResult(List<T> list, T[] array, String callback)
    {
        AjaxResult result = new AjaxResult();
        result.setTotal(list.size());
        result.setRows(list.toArray(array));
        result.setCallback(callback);
        return result;
    }

    public static boolean isAjaxReturn(Method method)
    {
        Class clazz = method.getReturnType();
        return !(clazz.equals(String.class) || clazz.equals(ModelAndView.class));
    }

    public static <T> T getPrincipal(PrincipalCapsule principalCapsule)
    {
        return principalCapsule == null ? null : (T)principalCapsule.getPrincipal();
    }
}
